package com.isoft.mapper;

import com.isoft.entity.DfmeAfidEntity;
import org.apache.ibatis.annotations.*;

/**
 * DFME-AFID消息数据访问接口
 * 提供对MSG_META和FLIGHT_BASE表的CRUD操作
 */
@Mapper
public interface DfmeAfidMapper {

    /**
     * 插入消息元数据（使用数据库自增主键）
     * @param entity 包含元数据的实体
     */
    @Insert({
            "INSERT INTO MSG_META(",
            "SENDER, RECEIVER, SEQUENCE_NUMBER, DATE_TIME, MSG_TYPE, SUB_TYPE)",
            "VALUES(",
            "#{meta.sender,jdbcType=VARCHAR},",
            "#{meta.receiver,jdbcType=VARCHAR},",
            "#{meta.sequenceNumber,jdbcType=BIGINT},",
            "TO_TIMESTAMP(#{meta.dateTime,jdbcType=VARCHAR}, 'yyyymmddhh24miss'),",
            "#{meta.type,jdbcType=VARCHAR},",
            "#{meta.subType,jdbcType=VARCHAR})"
    })
    @Options(useGeneratedKeys = true, keyProperty = "meta.msgId", keyColumn = "MSG_ID")
    void insertMeta(DfmeAfidEntity entity);

    // ==================== 方案2：手动生成ID（兼容方案） ====================
    /**
     * 插入消息元数据（手动生成ID）
     * @param entity 包含元数据的实体
     * @return 影响的行数
     */
    @Insert({
            "INSERT INTO MSG_META(",
            "MSG_ID, SENDER, RECEIVER, SEQUENCE_NUMBER, DATE_TIME, MSG_TYPE, SUB_TYPE)",
            "SELECT COALESCE(MAX(MSG_ID), 0) + 1,",
            "#{meta.sender,jdbcType=VARCHAR},",
            "#{meta.receiver,jdbcType=VARCHAR},",
            "#{meta.sequenceNumber,jdbcType=BIGINT},",
            "TO_TIMESTAMP(#{meta.dateTime,jdbcType=VARCHAR}, 'yyyymmddhh24miss'),",
            "#{meta.type,jdbcType=VARCHAR},",
            "#{meta.subType,jdbcType=VARCHAR}",
            "FROM MSG_META"
    })
    @SelectKey(
            statement = "SELECT COALESCE(MAX(MSG_ID), 0) FROM MSG_META",
            keyProperty = "msgId",
            before = true,
            resultType = Long.class
    )
    int insertMetaWithManualId(DfmeAfidEntity entity);

    // ==================== 方案3：使用序列（达梦特殊语法） ====================
    /**
     * 插入消息元数据（使用序列）
     * @param entity 包含元数据的实体
     */
    @Insert({
            "INSERT INTO MSG_META(",
            "MSG_ID, SENDER, RECEIVER, SEQUENCE_NUMBER, DATE_TIME, MSG_TYPE, SUB_TYPE)",
            "VALUES(",
            "(SELECT NEXT VALUE FOR SEQ_META FROM DUAL),",
            "#{meta.sender,jdbcType=VARCHAR},",
            "#{meta.receiver,jdbcType=VARCHAR},",
            "#{meta.sequenceNumber,jdbcType=BIGINT},",
            "TO_TIMESTAMP(#{meta.dateTime,jdbcType=VARCHAR}, 'yyyymmddhh24miss'),",
            "#{meta.type,jdbcType=VARCHAR},",
            "#{meta.subType,jdbcType=VARCHAR})"
    })
    @SelectKey(
            statement = "SELECT NEXT VALUE FOR SEQ_META FROM DUAL",
            keyProperty = "msgId",
            before = true,
            resultType = Long.class
    )
    void insertMetaWithSequence(DfmeAfidEntity entity);

    // ==================== 航班基础信息操作 ====================
    /**
     * 插入航班基础信息
     * @param entity 包含航班数据的实体
     * @return 影响的行数
     */
    @Insert({
            "INSERT INTO FLIGHT_BASE(",
            "FLIGHT_ID, FLIGHT_FILE_ID, FLIGHT_IDENTIFIER, HBID)",
            "VALUES(",
            "#{dflt.flightId,jdbcType=BIGINT},",
            "#{dflt.flightFileId,jdbcType=VARCHAR},",
            "#{dflt.flightIdentifier,jdbcType=VARCHAR},",
            "#{dflt.alternateFlightId,jdbcType=BIGINT})"
    })
    int insertFlightBase(DfmeAfidEntity entity);

    /**
     * 更新航班备降信息
     * @param entity 包含更新数据的实体
     * @return 影响的行数
     */
    @Update({
            "UPDATE FLIGHT_BASE SET",
            "HBID = #{dflt.alternateFlightId,jdbcType=BIGINT}",
            "WHERE FLIGHT_ID = #{dflt.flightId,jdbcType=BIGINT}"
    })
    int updateFlightBase(DfmeAfidEntity entity);

    // ==================== 查询操作 ====================
    /**
     * 根据航班ID查询是否存在记录
     * @param flightId 航班ID
     * @return 存在返回1，否则返回0
     */
    @Select("SELECT COUNT(1) FROM FLIGHT_BASE WHERE FLIGHT_ID = #{flightId}")
    int existsByFlightId(@Param("flightId") Long flightId);

    /**
     * 获取当前序列值（备用）
     * @return 当前序列值
     */
    @Select("SELECT CURRENT_VALUE FROM SYS.SYSSEQUENCES WHERE SEQNAME = 'SEQ_META'")
    Long getCurrentSequenceValue();

    /**
     * 获取下一个序列值（备用）
     * @return 下一个序列值
     */
    @Select("SELECT NEXT VALUE FOR SEQ_META FROM DUAL")
    Long getNextSequenceValue();

    /**
     * 插入航班异常信息
     * @param entity 包含异常数据的实体
     * @return 影响的行数
     */
    @Insert("INSERT INTO FLIGHT_IRREGULARITY(" +
            "FLIGHT_ID, ABNORMAL_STATUS, ABNORMAL_REASON, " +
            "INTERNAL_STATUS, INTERNAL_REASON, MANUAL_ABNORMAL_STATUS, MANUAL_ABNORMAL_REASON, " +
            "MANUAL_INTERNAL_STATUS, MANUAL_INTERNAL_REASON) " +
            "VALUES(" +
            "#{dflt.flightId,jdbcType=NUMERIC}, " +
            "'AFID', " +
            "NULL, " +
            "'AFID', " +
            "NULL, " +
            "NULL, NULL, NULL, NULL)")
    int insertIrregularity(DfmeAfidEntity entity);
}